package com.cvtt.xmpp.cvttmessage;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.util.Log;

import com.cvtt.xmpp.XMPPConfig;

public class CVTTMessageParser {

	CVTTMessage cvttMsg;

	public CVTTMessageParser(String contentxml) {
		cvttMsg = parse(contentxml);
		if(XMPPConfig.LOG_ENABLE)
		{
			Log.d("ss", cvttMsg.getContent());
			Log.d("sss", cvttMsg.toXML());
		}
	}

	public CVTTMessage getCVTTMessage() {
		return cvttMsg;
	}

	public boolean isCVTTMessage(String xml) {
		if (xml.indexOf("cvttmessage") >= 0)
			return true;
		return false;
	}

	private CVTTMessage parse(String parseXml) {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader xmlReader = parser.getXMLReader();
			CVTTMessageParseHandler handler = new CVTTMessageParseHandler();
			xmlReader.setContentHandler(handler);
			StringReader read = new StringReader(parseXml);
			InputSource source = new InputSource(read);
			xmlReader.parse(source);
			read.close();
			return handler.getCVTTMessage();
		}
		catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
